package com.wolf.client;

import com.wolf.constant.WolfConst;
import com.wolf.core.Header;
import com.wolf.core.Protocol;
import com.wolf.core.RequestEntity;
import com.wolf.enums.Command;
import com.wolf.enums.SerialEnum;
import com.wolf.serialization.SerialFactory;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;

/**
 * @auth: dylan
 * @Desc:
 * @Time: 2024/5/1
 */
public class WolfProxyInvocationHandler implements InvocationHandler {
    private String host;
    private int port;

    public WolfProxyInvocationHandler(String host,int port) {
        this.port = port;
        this.host=host;
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        //rpc调用,返回请求结果
        WolfNettyClient client=new WolfNettyClient(host,port);

        //构建发送数据包
        Protocol<RequestEntity> protocol=new Protocol<>();
        Header header=Header.builder().magic(WolfConst.magic)
                .serialId(Holder.serialFactory.get())
                .serialType(SerialEnum.JSON.getType())
                .command(Command.REQUEST.getCode()).build();
        RequestEntity request=new RequestEntity();
        request.setClazz(method.getDeclaringClass());
        request.setParamTypes(method.getParameterTypes());
        request.setParams(args);
        request.setMethodName(method.getName());
        byte[] bytes = new SerialFactory().get(SerialEnum.JSON.getType()).serializer(request);
        header.setDataLength(bytes.length);
        protocol.setHeader(header);
        protocol.setContent(request);
        return client.sendRequest(protocol);
    }
}
